package server

import (
	commentV1 "user/api/comment/v1"
	v1 "user/api/user/v1"
	wsV1 "user/api/ws/v1"
	"user/internal/conf"
	"user/internal/service"

	"github.com/go-kratos/kratos/v2/log"
	"github.com/go-kratos/kratos/v2/middleware/recovery"
	"github.com/go-kratos/kratos/v2/transport/http"
)

// NewHTTPServer new an HTTP server.
func NewHTTPServer(c *conf.Server, userService *service.UserService, logger log.Logger, wsServer *WsServer, commentService *service.CommentService, chatService *service.ChatServiceService) *http.Server {

	var opts = []http.ServerOption{
		http.Middleware(
			recovery.Recovery(),
		),
	}
	if c.Http.Network != "" {
		opts = append(opts, http.Network(c.Http.Network))
	}
	if c.Http.Addr != "" {
		opts = append(opts, http.Address(c.Http.Addr))
	}
	if c.Http.Timeout != nil {
		opts = append(opts, http.Timeout(c.Http.Timeout.AsDuration()))
	}

	srv := http.NewServer(opts...)
	v1.RegisterUserHTTPServer(srv, userService)
	srv.HandleFunc("/ws", wsServer.HandleWS)
	// 注册评论服务
	commentV1.RegisterCommentServiceHTTPServer(srv, commentService)
	// 注册聊天服务
	wsV1.RegisterChatServiceHTTPServer(srv, chatService)

	// 启动 WebSocket ping 协程
	wsServer.StartPingAllClients()

	return srv

}
